package com.xjj.serviceattend.config;

import com.rabbitmq.client.AMQP;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: AYang
 * @Date: 2022/10/26 14:07
 * @Description: RabbitMq配置类
 */
@Configuration
public class MqConfig {
    /**
     * 获取当前时间到午夜时间的秒数（单位：秒s）
     * @return
     */
    public int getSecondNumber() {
        LocalTime midnight = LocalTime.MIDNIGHT;
        LocalDate today = LocalDate.now();
        LocalDateTime todayMidnight = LocalDateTime.of( today, midnight );
        LocalDateTime tomorrowMidnight = todayMidnight.plusDays( 1 );
        long seconds = TimeUnit.NANOSECONDS.toSeconds( Duration.between( LocalDateTime.now(), tomorrowMidnight ).toNanos() );
        return (int) seconds;
    }

    /**
     * 死信队列，实现延迟队列
     * 一组交换机和队列，队列没有消费者，让它变成死信
     * @return
     */
    // 声明交换机
    @Bean
    public TopicExchange exchangeAttendDelay(){
        return new TopicExchange("exchangeAttendDelay");
    }

    // 声明队列
    @Bean
    public Queue queueAttendDelay(){
        Map<String,Object> arguments = new HashedMap<>();
        int time = getSecondNumber();
        time = time * 1000;
        // 过期时间(毫秒)：延迟多久，消费者开始处理消息
        arguments.put("x-message-ttl",time);
        // 死信交换机：变成死信以后，进入那个交换机
        arguments.put("x-dead-letter-exchange","exchangeAttendDlx");
        // 由哪个路由去投
        arguments.put("x-dead-letter-routing-key","attendDlx");
        return new Queue("queueAttendDelay",true,false,false,arguments);
    }

    // 绑定队列
    @Bean
    public Binding bindingAttendDelay(Queue queueAttendDelay,TopicExchange exchangeAttendDelay) {
        return BindingBuilder.bind(queueAttendDelay).to(exchangeAttendDelay).with("#.attendDelay.#");
    }

    // 声明交换机
    @Bean
    public TopicExchange exchangeAttendDlx(){
        return new TopicExchange("exchangeAttendDlx");
    }

    // 声明队列
    @Bean
    public Queue queueAttendDlx(){
        return new Queue("queueAttendDlx");
    }

    // 绑定队列
    @Bean
    public Binding bindingAttendDlx(Queue queueAttendDlx,TopicExchange exchangeAttendDlx) {
        return BindingBuilder.bind(queueAttendDlx).to(exchangeAttendDlx).with("#.attendDlx.#");
    }
}
